<!--
 * @Author: ITDLCL
 * @Date: 2024-11-11 14:04:24
 * @LastEditors: ITDLCL
 * @Description:
-->
<!-- 互动支付弹窗 -->
<template>
  <view class="activity-popup">
    <van-popup
      :show="showPopup"
      :lock-scroll="true"
      position="bottom"
      custom-style="height: 86.34%;z-index: 10000"
      overlay-style="z-index:1000"
      @touchmove.stop.prevent="moveHandle"
    >
      <view class="ctx">
        <view class="hd d-flex">
          <image
            src="https://bac-miniprogram.oss-cn-beijing.aliyuncs.com/images/icon/back_icon.png"
            mode="widthFix"
            @click="submitFunction('', 'back')"
          ></image>
          <text v-if="statusItem.shou_title" class="siyuan-medium">{{ statusItem.name }}</text>
          <van-icon name="cross" size="22px" color="#000000" @click="close()" />
        </view>
        <view class="ctx_container hide-scroll" :class="`ctx_container_item${statusItem.status}`">
          <!-- check order -->
          <template v-if="itemData.actStartTime">
            <CheckActive
              v-if="!statusItem.status"
              v-model:order-data="orderData"
              @submitClick="submitFunction()"
              :item-data="itemData"
            />
          </template>

          <!-- Qr code for admission -->
          <view class="qr-code" v-if="statusItem.status == 2">
            <image :src="itemData.verifyCodeUrl" mode="heightFix" class="user-select"></image>
          </view>
          <!--Pay status-->
          <view class="pay-status" v-if="[3, 4, 5, 6].includes(statusItem.status)">
            <PayStatus :pay-info="statusItem" />
            <label class="time" v-if="statusItem.status == 3">
              还剩
              <text class="intel-one-mono-regular">{{ timeData.minutes }}</text>
              分
              <text class="intel-one-mono-regular">{{ timeData.seconds }}</text>
              秒
            </label>
          </view>

          <!-- Activity introduction -->
          <view
            class="active-info border-top border-bottom d-flex"
            v-if="statusItem.img_style"
            :style="statusItem.img_bl"
          >
            <view
              v-if="itemData.actPictureUrlErect"
              class="thumb bg-cover border-right"
              :style="{
                ...statusItem.img_style,
                backgroundImage: 'url(' + itemData.actPictureUrlErect + ')',
              }"
            ></view>
            <view
              v-else-if="itemData.productPictureUrl"
              class="thumb bg-cover border-right"
              :style="{
                ...statusItem.img_style,
                backgroundImage: 'url(' + itemData.productPictureUrl + ')',
              }"
            ></view>
            <view class="lf-info" :class="{ 'small-info': statusItem.status != 1 }">
              <view class="title siyuan-medium">
                {{ itemData.title }}
              </view>
              <view class="time intel-one-mono-regular">
                {{ orderData.currentDay }}
                <br v-if="statusItem.is_line_feed" />
                15:00-16:00
              </view>
              <button v-if="!statusItem.is_line_feed" class="black-btn" @click="close()">
                查看详情
              </button>
            </view>
          </view>
          <!--order info-->
          <view class="order-list" v-if="statusItem.status > 0">
            <OrderCell
              :list="statusItem.status == 1 ? orderInfo.slice(0, 2) : orderInfo.slice(0, 4)"
            />
          </view>
          <view class="order-list" v-if="statusItem.status > 1">
            <OrderCell
              :list="statusItem.status == 2 ? orderInfo.slice(4) : orderInfo.slice(4, 8)"
            />
          </view>

          <!--Pay Methods-->
          <Pay
            v-if="statusItem.status == 1"
            :pay-info="orderPayMethod"
            @changeType="type => (orderPayMethod.type = type)"
          />
          <view class="protocol" v-if="statusItem.status == 1">
            <label
              for=""
              @click="
                submitFunction('', 'page', { url: '/pages/personal/agreement?source_type=service' })
              "
            >
              购票即代表阅读并同意《服务条款》
            </label>
          </view>
        </view>

        <!--no pay Protocol-->
        <Option>
          <template v-slot:btn>
            <view class="protocol" v-if="statusItem.status == 1">
              <button class="black-btn" @click="submitFunction()">确认支付</button>
            </view>
            <!--Pay Options-->
            <view class="pay-option d-flex border-bottom border-top" v-if="statusItem.status == 3">
              <button class="black-btn" @click="canclePay()">取消支付</button>
              <button class="black-btn" @click="createPay({ orderNo: orderNo }, 'cancle')">
                确认支付
              </button>
            </view>
          </template>
        </Option>
      </view>
    </van-popup>
  </view>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import Option from "@/components/FooterBar/Option.vue";
import CheckActive from "../Modules/CheckActive.vue";
import OrderCell from "../List/OrderCell.vue";
import Pay from "../Modules/Pay.vue";
import PayStatus from "../Tags/PayStatus.vue";
import { setOrderSave, getOrderPay, getOrderCancle } from "@/server/api.js";
import { payClick } from "@/util/pay.js";

const props = defineProps({
  showPopup: {
    type: Boolean,
    default: true,
  },
  statusItem: {
    type: Object,
    default: {},
  },
  count: {
    type: Number,
    default: 0,
  },
  itemData: {
    type: Object,
    default: {},
  },
  orderNo: {
    type: String,
    default: "",
  },
  pointData: {
    type: Object,
    default: {},
  },
});
let orderData = ref({});
let productInfo = ref({});
let orderInfo = ref([
  { name: "单人票", feile: "ticket", data: "10.00 x 1" },
  { name: "合计", feile: "sum", data: "10.00" },
  { name: "支付方式", feile: "pay_method", data: "积分支付" },
  { name: "积分抵扣", feile: "point_deduction", data: "+2" },
  { name: "姓名", feile: "name", data: "liuhaha" },
  { name: "手机号", feile: "phone", data: "18852412356" },
  { name: "订单编号", feile: "order_number", data: "A2024121212121212" },
  { name: "下单时间", feile: "order_time", data: "2024-08-21 11:00:48" },
  { name: "使用方式", feile: "use_method", data: "使用会员码核销" },
]);

let orderPayMethod = ref({}); // 微信或者积分下单的信息
let timeInteral = null; // 时间控制器
let timeData = ref({}); // 倒计时

watch(orderData, val => {
  let payMethod = pointPay(val.actPriceVOList.actPrice, val.number);
  orderPayMethod.value = {
    ...payMethod,
    price: val.actPriceVOList.actPrice,
    number: val.number,
  };
  let info = orderInfo.value;
  info[0].data = val.actPriceVOList.actPrice + " x " + val.number;
  info[0].name = val.actPriceVOList.priceName;
  info[1].data = val.actPriceVOList.actPrice * val.number;
  orderInfo.value = info;
});

watch(
  () => props.showPopup,
  val => {
    !val ? clearInterval(timeInteral) : "";
  }
);

watch(
  () => props.itemData,
  val => {
    handleMenuList();
  }
);

let emits = defineEmits(["update:count", "update:showPopup", "changeOrder"]);

// 微信支付
const wechatPay = params => {
  let { orderNo = "" } = productInfo.value;
  payClick(params)
    .then(res => {
      emits("update:count", props.statusItem.next_status);
      emits("changeOrder", orderNo);
    })
    .catch(res => {
      // 支付失败
      emits("update:count", 3);
      emits("changeOrder", orderNo);
    });
};

// 支付
const createPay = (type, params) => {
  let { orderNo = "" } = productInfo.value;
  if (type == "cancle") {
    uni.showLoading({
      title: "加载中",
    });
  }
  getOrderPay({
    orderNo: orderNo,
    payMethod: params.type || 1,
  }).then(res => {
    if (res.code == 2000) {
      if (params.type == 2) {
        // 积分支付
        uni.hideLoading();
        uni.showToast({
          title: "支付成功",
          icon: "none",
        });
        emits("update:count", 2);
        emits("changeOrder", orderNo);
      } else {
        // 唤起微信支付
        wechatPay(res.data);
      }
    } else {
      wx.hideLoading({});
      uni.showToast({
        title: res.msg,
        icon: "none",
      });
    }
  });
};

// 判断是否符合积分下单
const pointPay = (price, number) => {
  let needPay = price * number * props.pointData.pointExchangeRate;
  let maxPoint = props.itemData.maxDeductPoint || 0;
  console.log('是否可以支付',props.pointData.point,needPay,maxPoint)
  if (props.pointData.point > needPay  && maxPoint >= needPay) {
    return {
      type: 2,
      count: needPay,
      cash: price * number,
      noClick: true,
	  checkPoint: true
    };
  } else {
    return {
      type: 1,
      count: needPay,
      cash: price * number,
      noClick: false,
	  checkPoint: maxPoint >= needPay// 是否高比例抵扣
    };
  }
};

const submitFunction = (status, type, params) => {
  let { orderNo = "" } = productInfo.value;
  if (type == "page") {
    uni.navigateTo({
      url: params.url,
    });
    return;
  }

  if (type == "back") {
    console.log(props.statusItem.back_status);
    props.statusItem.back_status ? emits("update:count", props.statusItem.back_status) : close();
    return;
  }

  if (props.statusItem.status == 1) {
    // 下单
    uni.showLoading({
      title: "加载中",
    });
    setOrderSave({
      actId: props.itemData.id,
      actPriceId: orderData.value.actPriceVOList.id,
      number: orderData.value.number,
      orderPrice: orderData.value.actPriceVOList.actPrice * orderData.value.number,
      pointDeduction: orderPayMethod.value.type == 1 ? 0 : orderPayMethod.value.count,
      productType: 1,
      // payMethod: orderPayMethod.value.type,
      endTime: orderData.value.currentDay + " 23:59:59",
      startTime: orderData.value.currentDay + " 00:00:00",
      productName: props.itemData.title,
      productPictureUrl: props.itemData.actPictureUrlErect,
    }).then(res => {
      if (res.code == 2000) {
        productInfo.value = res.data;
        createPay("", orderPayMethod.value);
        // emits("update:count", props.statusItem.next_status);
      } else {
        wx.hideLoading({});
        uni.showToast({
          title: res.msg,
          icon: "none",
        });
      }
    });
    return;
  }

  if (props.statusItem.next_status) {
    emits("update:count", props.statusItem.next_status);
    props.statusItem.status != 0 ? emits("changeOrder", orderNo) : "";
    return;
  }
};

const close = () => {
  emits("update:showPopup", false);
  emits("update:count", 0);
};

function handleMenuList() {
  if (!props.itemData.orderNo) {
    return;
  }
  productInfo.value.orderNo = props.orderNo;
  let info = orderInfo.value;
  info[0].data = `${props.itemData.actPrice} x ${props.itemData.number}`;
  info[0].name = props.itemData.priceName;
  info[1].data = props.itemData.orderPrice;
  info[2].data = props.itemData.pointDeduction ? "积分抵扣" : "微信支付";
  info[3].data = props.itemData.pointDeduction || 0;
  info[4].data = props.itemData.nickname;
  info[5].data = props.itemData.phone;
  info[6].data = props.itemData.orderNo;
  info[7].data = props.itemData.orderTime;
  info[8].data = "使用会员码核销";
  orderInfo.value = info;

  // 处理倒计时
  if (props.itemData.orderStatus == 0 && props.statusItem.status == 3) {
    let lastTime = props.itemData.latestPayTime.replaceAll("-", "/");
    timeInteral = setInterval(() => {
      let targetDate = new Date(lastTime);
      let currentDate = new Date();
      let remainingTime = targetDate - currentDate;
      if (remainingTime <= 0) {
        clearInterval(timeInteral); // 停止定时器
        timeData.value = {
          minutes: 0,
          seconds: 0,
        };
        return;
      }
      // let hours = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      let minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
      let seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);
      timeData.value = {
        minutes: minutes,
        seconds: seconds,
      };
    }, 1000);
  }
}

// 取消支付
function canclePay() {
  let { orderNo = "" } = productInfo.value;
  getOrderCancle({
    orderNo: orderNo,
  }).then(res => {
    if (res.code == 2000) {
      emits("update:count", 4);
      emits("changeOrder", orderNo);
    }
  });
}

onMounted(() => {
  handleMenuList();
});
function moveHandle() {}
</script>

<style lang="scss" scoped>
.activity-popup {
  .ctx {
    position: relative;
    height: 100%;
    padding: 0 20rpx;
    .ctx_container {
      position: absolute;
      top: 126rpx;
      left: 0;
      width: 100%;
      height: calc(100% - 126rpx);
      padding: 0 20rpx;
      overflow: hidden;
      overflow-x: hidden;
      overflow-y: scroll;
    }
    .ctx_container_item0 {
      padding-bottom: 340rpx;
    }
    .ctx_container_item1,
    .ctx_container_item3 {
      padding-bottom: 160rpx;
    }
  }
  .hd {
    position: absolute;
    left: 0;
    width: 100%;
    height: 126rpx;
    padding: 0 40rpx 0 44rpx;
    align-items: center;
    justify-content: space-between;
    image {
      width: 46rpx;
    }
    text {
      font-size: 32rpx;
    }
  }
  .active-info {
    .thumb {
      flex-shrink: 1;
    }
    .lf-info {
      position: relative;
      padding: 40rpx 40rpx 0 34rpx;
      flex: 1;
      .title {
        min-height: 144rpx;
        font-size: 34rpx;
        line-height: 40rpx;
      }
      .time {
        margin-top: 136rpx;
        font-size: 26rpx;
      }
      button {
        position: absolute;
        left: 0;
        bottom: -2rpx;
        width: 100%;
        height: 102rpx;
        padding-left: 26rpx;
        line-height: 102rpx;
        text-align: left;
        font-size: 24rpx;
      }
    }
    .lf-info.small-info {
      padding: 20rpx 26px 0 20rpx;
      .title {
        min-height: 62rpx;
        font-size: 24rpx;
        line-height: 30rpx;
      }
      .time {
        margin-top: 60rpx;
      }
    }
  }
  .protocol {
    padding-top: 46rpx;
    text-align: center;
    label {
      font-size: 20rpx;
    }
    button {
      width: 300rpx;
      height: 102rpx;
      margin-top: 26rpx;
      line-height: 102rpx;
    }
  }
  .qr-code {
    padding-bottom: 40rpx;
    text-align: center;
    image {
      height: 222rpx;
    }
  }
  .pay-option {
    button:first-child {
      width: 170rpx;
      background-color: #ffffff;
      color: var(--default-text);
    }
    button {
      height: 102rpx;
      line-height: 102rpx;
    }
    button + button {
      flex: 1;
    }
  }
  .pay-status {
    // margin-top: -10px;
    text-align: center;
    .time {
      display: inherit;
      margin-bottom: 46rpx;
      font-size: 20rpx;
    }
  }
}
:global(.van-overlay) {
  z-index: 1000;
}
</style>
